/*
* Copyright 2010 Dovado FZ-LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#import "MapViewController.h"
#import "DovadoAppDelegate.h"
#import "DialogUtils.h"
#import "Info.h"

@implementation MapViewController
@synthesize mNetworkRequest;
@synthesize mMapView;
@synthesize mMapPinAnnotation;
/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        // Custom initialization
    }
    return self;
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	mMapPinAnnotation = nil;
	mNetworkRequest = NULL;
}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (IBAction) onRefreshButtonClicked {
	NSLog(@"MapView : onRefreshButtonClicked");
	if (mNetworkRequest != NULL) {
		request_error_codes_t errorCode = [mNetworkRequest requestInfo];
		if (errorCode == REQUEST_OK) {
			mProgressAlert = [DialogUtils createProgressionAlertWithTitle:NSLocalizedString(@"info_dialog_title", @"Please wait") 
															   andMessage: NSLocalizedString(@"info_dialog_message", @"Downloading router information")];	
		} else {
			[DialogUtils showConnectionFailedDialog:errorCode];
		}
	} else {
		NSLog(@"mNetworkRequest is NULL");
	}
}

- (IBAction) onLoginButtonClicked {
	DovadoAppDelegate *appDelegate = (DovadoAppDelegate*) [[UIApplication sharedApplication] delegate];
	[appDelegate.window addSubview:appDelegate.mLoginViewController.view];
    [appDelegate.window makeKeyAndVisible];
}

- (void)viewDidAppear:(BOOL)animated {
	
	if(mMapPinAnnotation != nil) {
		[mMapView removeAnnotation:mMapPinAnnotation];
	}
	
	DovadoAppDelegate* delegate = (DovadoAppDelegate*) [[UIApplication sharedApplication] delegate];
	CLLocationCoordinate2D cord = delegate.mRouterLocation;

	MKCoordinateSpan span;
	span.latitudeDelta = 0.1;
	span.longitudeDelta = 0.1;		

	if(cord.latitude == 37.0f && cord.longitude == -20.0f){
		span.latitudeDelta = 130;
		span.longitudeDelta = 130;
	}
	
	MKCoordinateRegion region;
	region.center = cord;
	region.span = span;
	
	mMapPinAnnotation = [[MyMapAnnotation alloc] init];
	mMapPinAnnotation.coordinate = cord;
	
	[mMapView addAnnotation:mMapPinAnnotation];
	[mMapView setZoomEnabled:TRUE];
	[mMapView setRegion:region];

	
	if (![delegate extendedFeatures]) {
			[DialogUtils showNotSupportedDialog];
	} else {
		if (mNetworkRequest == NULL) {
			mNetworkRequest = [[DovadosNetworkRequest alloc] initWithHost: delegate.mHostAddress :6435];
		} else {
			[mNetworkRequest setMHost:delegate.mHostAddress];
		}
		[mNetworkRequest setUserInformation:delegate.mUser :delegate.mPassword: self];
	}
	
	[mMapPinAnnotation release];
}

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
	static NSString *defaultPinID = @"Router location";
	MKPinAnnotationView *retval = nil;
	
	if ([annotation isMemberOfClass:[MyMapAnnotation class]]) {
		retval = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
		if (retval == nil) {
			retval = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:defaultPinID] autorelease];
		}
		
		if (retval) {
			[retval setPinColor:MKPinAnnotationColorGreen];
			retval.animatesDrop = YES;
			retval.canShowCallout = NO;
			
		}
	}
	
    return retval;
}

- (void) infoRequestDone: (NSMutableArray*) infoArray {
	/* Parse the info */
	// Read the GPS lat/lon from the router. 
	DovadoAppDelegate *appDelegate = (DovadoAppDelegate*) [[UIApplication sharedApplication] delegate];
	CLLocationCoordinate2D coords;
	coords.latitude = appDelegate.mRouterLocation.latitude;
	coords.longitude = appDelegate.mRouterLocation.longitude;
	for(Info *info in infoArray) {
		if([info.mName isEqualToString:@"GPS_LAT"]) {
			coords.latitude = [info.mValue floatValue];
		} else if([info.mName isEqualToString:@"GPS_LONG"]) {
			coords.longitude = [info.mValue floatValue];
		}
		
	}
	appDelegate.mRouterLocation = coords;
	
	[DialogUtils dismissAlert:mProgressAlert];
	mProgressAlert = NULL;	
}

- (void) dovadoRequestFailed: (request_listener_error_t) error_code: (NSString*) message {
	NSLog(@"dovadoRequestFailed error_code: %i message: %@", error_code, message);
	[DialogUtils dismissAlert:mProgressAlert];
	mProgressAlert = NULL;
	if(error_code == ERROR_UNKNOWN_ERROR) {
		UIAlertView *errorAlert = [[UIAlertView alloc]
								   initWithTitle: NSLocalizedString(@"on_result_exception_dialog_title", @"Network Error")
								   message: NSLocalizedString(@"error_unknown_error", @"Unknown error")
								   delegate:self
								   cancelButtonTitle:NSLocalizedString(@"no_button_text", @"No")
								   otherButtonTitles:NSLocalizedString(@"yes_button_text", @"Yes"), nil];
		((UILabel*)[[errorAlert subviews] objectAtIndex:1]).textAlignment = UITextAlignmentLeft;
		[errorAlert show];
		[errorAlert release];
	} else {
		[DialogUtils showOnConnectionResultErrorDialog:error_code];
	}
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[mMapView release];
    [super dealloc];
}


@end
